﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;

namespace iEN.Schedule
{
    public partial class Group : System.Web.UI.Page
    {
        #region protected void Page_Load(object sender, EventArgs e) //初始頁面
        protected void Page_Load(object sender, EventArgs e)
        {
            //clear cache
            Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            if (!this.Page.IsPostBack)//先判斷是否已經登入過
            {                
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }
                this.Intialize();
                //978
                gvGroupListBinding();
            }       
        }
        #endregion

        #region Initialization methods
        private void Intialize()
        {

            DataTable dtBillMode = new DBAccess().getBillModeTable();  //取得ALLTag
            Session["dtBillMode"] = dtBillMode;

            if (Session["SysAdmin"].ToString() != "2")
            {
                Panel1.Visible = false;
                btAddTag.Visible = false;
                lblMsg.Visible = true;
            }
        }
        #endregion

        //978
        private void gvGroupListBinding()
        {
            DBAccess_CHTD dbAccess = new DBAccess_CHTD();
            DataTable dtGroup = dbAccess.GetGroupInformation();
            //異常處理
            if (dbAccess.ErrMsg != string.Empty)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception: " + dbAccess.ErrMsg + "')", true);
            }
            else
            {
                gvGroupList.DataSource = dtGroup;
                gvGroupList.DataBind();
            }
        }

        #region protected void btAddTag_Click(object sender, EventArgs e)
        protected void btAddTag_Click(object sender, EventArgs e)
        {
            gvGroupList.SelectedIndex = -1;

            tbxGroupName.Text = "";
            lbxSource.Items.Clear();
            lbxTarget.Items.Clear();
            bindSchedulableMeter();
            btnOK.Text = "確認";
            Panel2.Visible = true;
        }
        #endregion

        //978
        private void bindSchedulableMeter()
        {
            DBAccess_CHTD dbAccess = new DBAccess_CHTD();
            DataTable dtMeters = dbAccess.GetPowerMeter4Schedule();
            //異常處理
            if (dbAccess.ErrMsg != string.Empty)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception: " + dbAccess.ErrMsg + "')", true);
            }
            else
            {
                if (dtMeters.Rows.Count > 0)
                {
                    foreach (DataRow row in dtMeters.Rows)
                    {
                        ListItem li = new ListItem(row["DeviceName"].ToString().Trim(), row["DeviceID"].ToString());
                        lbxSource.Items.Add(li);
                    }
                }
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            foreach(ListItem li in lbxSource.Items)
            {
                if(li.Selected == true)
                {
                    lbxTarget.Items.Add(new ListItem(li.Text, li.Value));
                    li.Enabled = false;
                }
            }

            //移除已加入之電錶
            for (int i = lbxSource.Items.Count - 1; i >= 0; i--)
            {
                if (lbxSource.Items[i].Enabled == false)
                    lbxSource.Items.RemoveAt(i);
            }
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            foreach (ListItem li in lbxTarget.Items)
            {
                if (li.Selected == true)
                {
                    lbxSource.Items.Add(new ListItem(li.Text, li.Value));
                    li.Enabled = false;
                }
            }

            //移除已加入群組之電錶
            for (int i = lbxTarget.Items.Count - 1; i >= 0; i--)
            {
                if (lbxTarget.Items[i].Enabled == false)
                    lbxTarget.Items.RemoveAt(i);
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            int groupID = -1;
            int meterCount = lbxTarget.Items.Count;
            bool isSuccessful = false;
            DBAccess_CHTD dbAccess = new DBAccess_CHTD();

            if (tbxGroupName.Text.Equals(""))
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('請輸入群組名稱')", true);
                return;
            }
            else if (meterCount == 0)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('請選擇電錶')", true);
                return;
            }
            else
            {
                int[] deviceIDs = new int[meterCount];

                for (int i = 0; i < meterCount; i++)
                {
                    deviceIDs[i] = Convert.ToInt32(lbxTarget.Items[i].Value);
                }
                //更新群組
                if (btnOK.Text.Equals("修改"))
                {
                    groupID = Convert.ToInt32(lbGroupID.Text);
                    isSuccessful = dbAccess.UpdateGroupInformationByGroupID(groupID, tbxGroupName.Text, deviceIDs);
                }
                else
                {
                    isSuccessful = dbAccess.InsertGroupInformationByGroupID(tbxGroupName.Text, deviceIDs);
                }
                if (isSuccessful == true)
                {
                    if (btnOK.Text.Equals("修改"))
                    {
                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組修改成功！')", true);
                        gvGroupList.SelectedIndex = -1;
                        //log, 修改排程群組
                        writeToLog(93, "電錶群組名稱：" + tbxGroupName.Text + "(電錶群組ID:" + groupID.ToString() + ")，修改成功！", "1", 0);
                    }
                    else
                    {
                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組新增成功！')", true);
                        //log, 新增排程群組
                        writeToLog(91, "電錶群組名稱:" + tbxGroupName.Text + "，新增成功！", "1", 0);
                    }
                    gvGroupListBinding();
                    Panel2.Visible = false;
                }
                else
                {
                    if (btnOK.Text.Equals("修改"))
                    {
                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組修改失敗！ " + dbAccess.ErrMsg + "')", true);
                        //log, 修改排程群組
                        writeToLog(93, "電錶群組名稱：" + tbxGroupName.Text + "(電錶群組ID:" + groupID.ToString() + ")，修改失敗！", "0", 0);
                    }
                    else
                    {
                        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組新增失敗！ " + dbAccess.ErrMsg + "')", true);
                        //log, 新增排程群組
                        writeToLog(91, "電錶群組名稱:" + tbxGroupName.Text + "，新增失敗！", "0", 0);
                    }
                }

            }

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Panel2.Visible = false;
            gvGroupList.SelectedIndex = -1;
            tbxGroupName.Text = "";
            lbxSource.Items.Clear();
            lbxTarget.Items.Clear();
        }

        protected void gvGroupList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int groupID = -1;
            DBAccess_CHTD dbAccess = new DBAccess_CHTD();

            lbxSource.Items.Clear();
            lbxTarget.Items.Clear();

            GridViewRow row = gvGroupList.SelectedRow;
            //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('group id: " + row.Cells[0].Text.Trim() + "')", true);
            groupID = Convert.ToInt32(row.Cells[0].Text.Trim());
            lbGroupID.Text = row.Cells[0].Text.Trim();
            tbxGroupName.Text = row.Cells[1].Text.Trim();
            //lbxSource
            bindSchedulableMeter();
            //lbxTarget
            DataTable dtTarget = dbAccess.GetPowerMeterByGroupID(groupID);
            //異常處理
            if (dbAccess.ErrMsg != string.Empty)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception: " + dbAccess.ErrMsg + "')", true);
            }
            else
            {
                foreach (DataRow dtrow in dtTarget.Rows)
                {
                    ListItem li = new ListItem(dtrow["DeviceName"].ToString().Trim(), dtrow["DeviceID"].ToString());
                    lbxTarget.Items.Add(li);
                }
                btnOK.Text = "修改";
                Panel2.Visible = true;
            }
        }

        //978, hide column GroupID
        protected void gvGroupList_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[0].Visible = false;
            }
        }

        protected void btnDelete_Command(object sender, CommandEventArgs e)
        {
            int groupID = -1;
            string groupName = "";
            int index = Convert.ToInt32(e.CommandArgument);
            bool isSuccessful = false;
            DBAccess_CHTD dbAccess = new DBAccess_CHTD();
            if (e.CommandName == "Delete")
            {
                groupID = Convert.ToInt32(gvGroupList.Rows[index].Cells[0].Text.Trim());
                groupName = gvGroupList.Rows[index].Cells[1].Text.Trim();
                isSuccessful = dbAccess.DeleteGroupInformationByGroupID(groupID);

                if (isSuccessful == true)
                {
                    //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組刪除成功！')", true);
                    gvGroupListBinding();
                    gvGroupList.SelectedIndex = -1;
                    Panel2.Visible = false;
                    //log, 刪除排程群組
                    writeToLog(92, "電錶群組名稱：" + groupName + "(電錶群組ID:" + groupID + ")，刪除成功！", "1", 0);
                }
                else
                {
                    //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('群組刪除失敗！ " + dbAccess.ErrMsg + "')", true);
                    //log, 刪除排程群組
                    writeToLog(92, "電錶群組名稱：" + gvGroupList.Rows[index].Cells[1].Text.Trim() + "(電錶群組ID:" + groupID.ToString() + ")，刪除失敗！", "0", 0);
                }
            }
        }

        protected void gvGroupList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvGroupList.PageIndex = e.NewPageIndex;
            gvGroupListBinding();
        }
        private void writeToLog(int event_category, string memo, string result, int org_group_id)
        {
            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            new DBAccess().addEventLog(strAccount, strIP, event_category, memo, result, org_group_id);
        }

    }
}